package com.lpf.mybatis.result;

import com.lpf.mybatis.config.Configuration;
import com.lpf.mybatis.config.MapperRegistry;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 功能描述：结果处理器
 *
 * 将从数据库查询出来的结果封装成对应实体
 */
@SuppressWarnings("all")
public class ResultSetHandler {

    private final Configuration configuration;

    public ResultSetHandler(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 功能描述：处理结果集数据
     */
    public <E> E handle(PreparedStatement pstmt, MapperRegistry.MapperData mapperData) throws Exception {

        // 通过反射进行实例化
        Object resultObj = mapperData.getType().newInstance();

        // 获取结果集
        ResultSet rs = pstmt.getResultSet();
        if (rs.next()) {
            for (Field field : resultObj.getClass().getDeclaredFields()) {
                setValue(resultObj, field, rs);
            }
        }
        return (E) resultObj;
    }

    /**
     * 功能描述：给属性赋值
     */
    private void setValue(Object resultObj, Field field, ResultSet rs) throws Exception {
        Method setMethod = resultObj.getClass().getMethod("set" + upperCapital(field.getName()), field.getType());
        setMethod.invoke(resultObj, getResult(field, rs));
    }

    private Object getResult(Field field, ResultSet rs) throws SQLException {

        //TODO type handles

        Class<?> type = field.getType();
        if (Integer.class == type) {
            return rs.getInt(field.getName());
        }
        if (String.class == type) {
            return rs.getString(field.getName());
        }
        return rs.getString(field.getName());
    }

    private String upperCapital(String name) {
        String first = name.substring(0, 1);
        String tail = name.substring(1);
        return first.toUpperCase() + tail;
    }
}
